// pages/admin/adoption-review/adoption-review.js
const { get, put } = require('../../../utils/request')
const { formatDate, showSuccess, showError, showConfirm } = require('../../../utils/util')

Page({
  data: {
    applicationId: null,
    applicationInfo: {},
    reviewResult: '', // 'approved' 或 'rejected'
    reviewNote: '',
    submitting: false,
    loading: true,
    canSubmit: false // 是否可以提交
  },

  onLoad(options) {
    // 检查管理员权限
    const app = getApp()
    if (!app.globalData.userInfo || app.globalData.userInfo.role !== 'ADMIN') {
      wx.showModal({
        title: '权限不足',
        content: '您没有管理员权限',
        showCancel: false,
        success: () => {
          wx.navigateBack()
        }
      })
      return
    }

    if (options.id) {
      this.setData({
        applicationId: options.id
      })
      this.loadApplicationDetail()
    } else {
      showError('参数错误')
      wx.navigateBack()
    }
  },

  // 加载申请详情
  loadApplicationDetail() {
    this.setData({ loading: true })

    get(`/adoption/${this.data.applicationId}`).then(res => {
      const applicationInfo = res.data
      
      // 格式化时间
      applicationInfo.createTime = formatDate(applicationInfo.createTime)
      if (applicationInfo.reviewTime) {
        applicationInfo.reviewTime = formatDate(applicationInfo.reviewTime)
      }

      this.setData({
        applicationInfo
      })

      // 设置页面标题
      wx.setNavigationBarTitle({
        title: `审核申请 - ${applicationInfo.petName}`
      })

    }).catch(err => {
      showError('加载申请信息失败')
      wx.navigateBack()
    }).finally(() => {
      this.setData({ loading: false })
    })
  },

  // 选择审核结果
  selectResult(e) {
    const result = e.currentTarget.dataset.result
    this.setData({
      reviewResult: result
    })
    this.updateCanSubmit()
  },

  // 审核备注输入
  onNoteInput(e) {
    this.setData({
      reviewNote: e.detail.value
    })
    this.updateCanSubmit()
  },

  // 更新提交按钮状态
  updateCanSubmit() {
    const { reviewResult, reviewNote } = this.data
    const canSubmit = !!(reviewResult && reviewNote && reviewNote.trim().length >= 5)
    this.setData({
      canSubmit
    })
  },

  // 表单验证
  validateForm() {
    if (!this.data.reviewResult) {
      showError('请选择审核结果')
      return false
    }

    if (!this.data.reviewNote.trim()) {
      showError('请填写审核备注')
      return false
    }

    if (this.data.reviewNote.trim().length < 5) {
      showError('审核备注至少需要5个字符')
      return false
    }

    return true
  },

  // 提交审核
  async onSubmit() {
    if (this.data.submitting) return

    if (!this.validateForm()) return

    const statusText = this.data.reviewResult === 'approved' ? '通过' : '拒绝'
    
    try {
      await showConfirm(`确定要${statusText}这个领养申请吗？`)
    } catch {
      return
    }

    this.setData({ submitting: true })

    const status = this.data.reviewResult === 'approved' ? '已通过' : '已拒绝'
    const reviewNote = this.data.reviewNote.trim()

    // 使用专门的审核接口
    const reviewUrl = `/adoption/review/${this.data.applicationId}?status=${encodeURIComponent(status)}&reviewNote=${encodeURIComponent(reviewNote)}`

    put(reviewUrl).then(res => {
      showSuccess(`审核${statusText}成功`)

      // 延迟返回上一页
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)

    }).catch(err => {
      showError(err.msg || '审核失败，请重试')
    }).finally(() => {
      this.setData({ submitting: false })
    })
  },

  // 取消
  onCancel() {
    wx.navigateBack()
  }
})
